//
//  HessianFormDataRequest.m
//  DecorationDesign
//
//  Created by 许开伟 on 14/12/8.
//  Copyright (c) 2014年 许开伟. All rights reserved.
//

#import "HessianFormDataRequest.h"
#import <netinet/in.h>
#import <CFNetwork/CFNetwork.h>
#import <SystemConfiguration/SCNetworkReachability.h>
@implementation HessianFormDataRequest
- (void)startRequestWithURL:(NSURL *)url andCompletionBlcok:(CompletedBlock)compBlock andFailedBlock:(FailedBlock)failBlock
{
    self.rpc = (id<DecorationServiceRPC>)[CWHessianConnection proxyWithURL:url protocol:@protocol(DecorationServiceRPC)];
    completedBlock = compBlock;
    failedBlock = failBlock;

    if ([self isNetworkReachable] == nil) {
        failedBlock();
    }else{
        
        id result = [_rpc invokeService:_postData];
        if (result) {
            
            completedBlock(result);
        }else{
            failedBlock();
        }
    }

    
}
- (NSString *)isNetworkReachable{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        return @"";
    }
    BOOL is3g = flags & kSCNetworkReachabilityFlagsIsWWAN;
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    if (isReachable && !needsConnection) {
        if (is3g == YES) {
            return NSLocalizedString(@"You are using Unicom WIFI network.", nil);
        }
        else
            return NSLocalizedString(@"You are using Unicom 3G network.", nil);
    }
    else
        return nil;
}
@end
